package cn.sdormitory.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.sdormitory.service.AppRepairService;
import cn.sdormitory.smartdor.dao.SdRepairDao;
import cn.sdormitory.smartdor.entity.SdRepair;
import cn.sdormitory.smartdor.service.RepairDeviceService;
import cn.sdormitory.smartdor.vo.DeviceVo;
import cn.sdormitory.smartdor.vo.RepairInfoVo;
import cn.sdormitory.smartdor.vo.RepairStaVo;
import cn.sdormitory.smartdor.vo.RepairVo;
import cn.sdormitory.sys.dao.SysDictDetailDao;
import cn.sdormitory.sys.dao.SysUserDao;
import cn.sdormitory.sys.entity.SysDictDetail;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.wx.utils.WXUtil;
import cn.sdormitory.wx.utils.WeatherDataCreator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @创建人：zhouyang
 * @创建时间：2021/10/27 23:47
 * @version：V1.0
 */
@Slf4j
@Service
public class AppRepairServiceImpl extends ServiceImpl<SdRepairDao, SdRepair> implements AppRepairService {
    @Resource
    private SdRepairDao sdRepairDao;
    @Resource
    private RepairDeviceService repairDeviceService;

    @Resource
    private SysDictDetailDao sysDictDetailDao;
    
    @Autowired
    WeatherDataCreator weatherDataCreator;
    
    @Autowired
    WXUtil wxUtil;
    
    @Value("${wxsmall.maintenance_create_template_id}")
    private String maintenance_create_template_id;
    
    @Resource
    private SysUserDao sysUserDao;

    @Override
    public List<RepairVo> findAppRepairByRepairUserId(Long userId) {
        List<RepairVo> repairVoList = sdRepairDao.findAppRepairByRepairUserId(userId);
//        if(repairVoList.size() == 0 || repairVoList == null){
            return repairVoList;
//        }
//        for(RepairVo item : repairVoList){
//
//        }
    }

    @Override
    public List<RepairVo> getAppRepair(String repairDate, String storey, String buildingNo) {
        return sdRepairDao.getAppRepair(repairDate,storey,buildingNo);
    }

    @Override
    public List<RepairVo> getAppRepairByBId(Long bdormitoryId, String repairDate) {
        return sdRepairDao.getAppRepairByBId(bdormitoryId,repairDate);
    }

    @Override
    public int create(SdRepair repair) {
        int result = sdRepairDao.insert(repair);
        
        LambdaQueryWrapper<SysDictDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictDetail::getDictType, "sys_building");
        queryWrapper.eq(SysDictDetail::getStatus, "1");
        queryWrapper.eq(SysDictDetail::getDictValue, repair.getBuildingNo());
        SysDictDetail sysDictDetail = sysDictDetailDao.selectOne(queryWrapper);
    
        LambdaQueryWrapper<SysDictDetail> queryDeviceWrapper = new LambdaQueryWrapper<>();
        queryDeviceWrapper.eq(SysDictDetail::getDictType, "dormitory_devices");
        queryDeviceWrapper.eq(SysDictDetail::getStatus, "1");
        queryDeviceWrapper.in(SysDictDetail::getId, repair.getDeviceIds());
        List<SysDictDetail> deviceDetails = sysDictDetailDao.selectList(queryDeviceWrapper);
        
        String deviceName = "其他";
        if (CollectionUtil.isNotEmpty(deviceDetails)) {
            List<String> collect = deviceDetails.stream().map(SysDictDetail::getDictLabel).collect(Collectors.toList());
            deviceName = String.join(",", collect);
        }
        
        //保存报修与设备关系
        repairDeviceService.insertRepairAndRepairDevice(repair.getId(), repair.getDeviceIds());
      
        // 发送微信推送给维修人员
        // 1.查找出维修人员
        List<SysUser> staffList = sysUserDao.getMaintenanceStaffList();
        
        // 2.给维修人员推送通知
        for (SysUser sysUser : staffList) {
            if (StringUtils.isEmpty(sysUser.getWxOpenId())) {
                log.info("维修人员:{} 还未完成微信绑定!", sysUser.getUsername());
                continue;
            }
    
            // 发送微信推送通知
            Map<String, Object> weatherDataMap = weatherDataCreator.createMaintenanceDataMap(
                    sysDictDetail.getDictLabel() + "-" + repair.getDormitoryNo(),
                    deviceName,
                    DateUtil.formatDateTime(new Date()));
            try {
                JSONObject jsonObject = wxUtil.sendInfo(sysUser.getWxOpenId(), maintenance_create_template_id
                            , weatherDataMap,"");
            } catch (Exception e) {
                log.error("发送微信推送失败.{}", e.getMessage());
            }
            
        }
        
        return result;
    }

    @Override
    public int update(Long id, SdRepair repair) {
        //先删除报修与设备关系
        repairDeviceService.delAndCreateDevice(repair.getId(), repair.getDeviceIds());
        return sdRepairDao.updateById(repair);
    }

    @Override
    public SdRepair getRepairInfoById(Long id) {
        return sdRepairDao.getRepairInfoById(id);
    }

    @Override
    public int updateStatus(Long id, String status) {
        SdRepair repair = new SdRepair();
        repair.setId(id);
        repair.setStatus(status);
        return sdRepairDao.updateById(repair);
    }

    @Override
    public List<DeviceVo> getAppDevice() {
        return sdRepairDao.getAppDevice();
    }

    @Override
    public RepairStaVo getAppRepairCount() {
        return sdRepairDao.getAppRepairCount();
    }

    @Override
    public List<RepairInfoVo> getAppNewRepairList() {
        return sdRepairDao.getAppNewRepairList();
    }

    @Override
    public List<RepairInfoVo> getAppProcessList() {
        return sdRepairDao.getAppProcessList();
    }

    @Override
    public List<RepairInfoVo> getAppHistoryRepList() {
        return sdRepairDao.getAppHistoryRepList();
    }

    @Override
    public List<RepairInfoVo> getAppHisRepListByBId(Long bdormitoryId) {
        return sdRepairDao.getAppHisRepListByBId(bdormitoryId);
    }

    @Override
    public List<RepairInfoVo> getNewRepairInfoById(Long bdormitoryId) {
        return sdRepairDao.getNewRepairInfoById(bdormitoryId);
    }

    @Override
    public List<RepairInfoVo> getAllRepairByCreatedBy(String username) {
        return sdRepairDao.getAllRepairByCreatedBy(username);
    }

    @Override
    public int deleteRepair(Long id, SdRepair repair) {
        //先删除报修与设备关系
        repairDeviceService.delAndCreateDevice(repair.getId(), repair.getDeviceIds());
        return sdRepairDao.deleteById(id);
    }
}
